//
//  RTJHomeController.m
//  RuiTaiJinProject
//
//  Created by jayson on 2018/11/26.
//  Copyright © 2018年 leewei. All rights reserved.
//

#import "RTJHomeController.h"
#import "RTJHomeHeaderView.h"
#import "RTJHomeCell.h"
#import "RTJQuickPayController.h"
#import "RTJTenderDetailsController.h"
#import "WSLRollView.h"
#import "RTJLoginOrRegisterController.h"
#import "RTJAutomaticBidDetailsController.h"
#import "RTJAutomaticBidController.h"
#import "RTJTenderDetailsController.h"
#import "RTJAutoMarkDetailsController.h"
#import "RTJHTMLViewController.h"
#import "RTJCheckVersionView.h"
#import "LewPopupViewAnimationFade.h"

#define KRollViewHeight 200

@interface WSLRollViewVerticalCell : WSLRollViewCell

@property (strong, nonatomic) UILabel * titleLabel;
@end

@interface RTJHomeController ()<HomeHeaderViewDelegate,UITableViewDelegate,UITableViewDataSource,AutoMarkDelegate>

@property (nonatomic,strong)RTJHomeHeaderView *headView;
@property (nonatomic, strong) HAutoScrollView *autoView;
@property (nonatomic, strong) NSMutableArray *data;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong)NSString *urlStr;
@property (nonatomic, strong) NSDictionary *dataSource;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tabTop;
@property (nonatomic,strong ) UIView *views;
@property (nonatomic,assign) BOOL isCheckVersion;
@end

@implementation RTJHomeController

-(NSMutableArray *)data {
    if (!_data) {
        _data = [NSMutableArray array];
    }
    
    return _data;
}

#pragma mark - Lazy
-(RTJHomeHeaderView *)headView {
    if (!_headView) {
        _headView = [RTJHomeHeaderView loadNib];
        _headView.delegate = self;
    }
    return _headView;
}

-(void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = YES;
    [self getUserInfo];

    [self.tableView reloadData];

}

-(void)viewDidAppear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = YES;
    
    if (_isCheckVersion) {

        return;
    }
    
    //获取当前版本号
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentAppVersion = infoDic[@"CFBundleShortVersionString"];
    
    //获取上次启动应用保存的appVersion
    NSString *version = [[NSUserDefaults standardUserDefaults] objectForKey:@"version"];
    //版本升级或首次登录
    if (version != nil ||[version isEqualToString:currentAppVersion]) {
        
      //检测APP版本
        [self checkversion];
    }

}

-(void)checkversion{
    
    [RTJNetWork asyncRequestWithURL:@"init/check_version" params:nil method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                RTJCheckVersionView *view = [RTJCheckVersionView defaultViewWithFrame:CGRectMake(0, 0, 280, 414) data:data];
                view.parentVC = self;
                [self lew_presentPopupView:view animation:[LewPopupViewAnimationFade new] backgroundClickable:NO];
                [self lew_presentPopupView:view animation:[LewPopupViewAnimationFade new] dismissed:^{
                    
                    NSLog(@"动画结束");
                    
                }];
                
                [view withSureClick:^(BOOL isUpdate) {
                    
                    self.isCheckVersion = YES;

                    if (isUpdate) {
                        
                        
//                        NSURL *appUrl = [NSURL URLWithString:@"www.baidu.com"];
//                        [[UIApplication sharedApplication] openURL:appUrl];
                        
                        NSString *urlStr =@"itms-apps://itunes.apple.com/cn/app/tao-bao-sui-shi-sui-xiang/id387682726?mt=8";
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
                        
                    }
                    
                }];
                
            }
        }
    }];
}

-(void)getUserInfo{
    
    if ([RTJUserTool isLogin]) {
        
        [RTJNetWork asyncRequestWithURL:@"user/get_user_info" params:@{@"id":[RTJUserTool getTheUserModel].user_id} method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
            
            if (success) {
                
                if ([data[@"status"]integerValue] == 1) {
                    
                    [RTJUserTool saveTheUserInfo:data[@"data"]];
                    
                    [self.tableView reloadData];
                    
                }else{
                    
                    [RTJUserTool loginOut];
                    [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",data[@"msg"]]];
                    
                    [self.tableView reloadData];
                    
                }
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
                
            }
            
            
        }];
        
    }
}

- (void)viewDidLoad {
    
    
    [super viewDidLoad];
    
    
    self.navigationController.navigationBarHidden = YES;
    
    self.tabTop.constant = screenH == 812 ? -20:0;
    _views = [[UIView alloc]initWithFrame:CGRectMake(0,0,screenW, screenH == 812 ? screenH*240/667:screenH*270/667)];
    [_views addSubview:self.headView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView=[UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight=300;
//    self.tableView.backgroundColor = [UIColor redColor];

    
//    NSArray * arr = @[@"2",@"1",@"1"];
//    NSMutableArray *data = [NSMutableArray array];
//    [data addObjectsFromArray:arr];
   
    
    self.tableView.mj_header = [CustomRefreshGifHeader headerWithRefreshingBlock:^{
        
        [self loadData];
        
    }];
    
    [self.tableView.mj_header beginRefreshing];


}

-(void)loadData{
    
    [SVProgressHUD  showWithStatus:nil];
    
    if(self.data.count == 0){
        
        [self.view showEmptyViewWithStr:@"" image:nil callback:nil];
        [self.tableView showEmptyViewWithStr:@"" image:nil callback:nil];

    }

    [RTJNetWork asyncRequestWithURL:@"init/index" params:nil method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];
        [self.view removeEmptyView];
        [self.tableView removeEmptyView];


        if (success) {
            
            
            if ([data[@"status"]integerValue] == 1) {
                
                self.dataSource = data[@"data"];
                [self.data removeAllObjects];
                [self.data addObject:data[@"data"]];
                self.tableView.tableHeaderView = self.views;

                
                [self.headView loadData:self.dataSource[@"banner_list"] noticelist:self.dataSource[@"notice_list"] HomeVC:self];
                
                [self.tableView reloadData];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",data[@"msg"]]];
                
                [self.view showEmptyViewWithStr:data[@"msg"] image:[UIImage imageNamed:@"kbylogo"] callback:^{
                    [self loadData];
                }];
                
            }
            
        }else{
            
            
            [self.view showEmptyViewWithStr:errorMsg image:[UIImage imageNamed:@"kbylogo"] callback:^{
                
                [self loadData];
            }];

        }
                
    }];
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.data.count!=0 ? 6 : 0;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.data.count) {
        
        if (section == 4) {
            
            if ([self.data[0][@"rec_deal"] isKindOfClass:[ NSArray class]]) {
            
                return [self.data[0][@"rec_deal"] count];
                
            }else{
                
                return 0;
            }
            
        }else if (section == 3){
            
            if ([self.data[0][@"rec_deal"] isKindOfClass:[ NSArray class]]) {
                
                return [self.data[0][@"rec_deal"] count]!=0 ? 1: 0;

            }else{
                
                return 0;
            }
            
        }else if (section == 2){

            return 3;
            
        }else if (section == 5){
            
            return 1;
            
        }else{

            if (section == 0) {
                
                return 0;
                
            }else if(section == 1){
                
                if ([self.data[0][@"new_deal"] isKindOfClass:[NSDictionary class]]){
                    
                    return 1;
                    
                }else{
                    
                    return 0;
                }
            }
            
            else{
                
                return 1;
            }
        }
        
    }else{
        
        return 0;

    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath. section == 2){
        
        if ([_dataSource[@"plan_list"] count] == 0) {
            
            if (indexPath.row == 0 || indexPath.row == 1) {
                
                return 0;
            }
            
            }
        }
            
    return UITableViewAutomaticDimension;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * ID = @"RTJHomeCell";

    RTJHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (indexPath.section == 0) {
        
        if (!cell) {
            
            cell = [[NSBundle mainBundle] loadNibNamed:@"RTJHomeCell" owner:self options:nil][0];
        }
        
    }else if (indexPath.section == 1){
        
        if (!cell) {
            
            cell = [[NSBundle mainBundle] loadNibNamed:@"RTJHomeCell" owner:self options:nil][1];
            
        }
        
    }else if (indexPath.section == 2){
        
        if (indexPath.row == 0) {
            
            if (!cell) {
                
                cell = [[NSBundle mainBundle] loadNibNamed:@"RTJHomeCell" owner:self options:nil][5];
                
            }
            cell.headerTitle.text = @"自动投标服务";

            
        }else if (indexPath.row == 1){
            
            if (!cell) {
                
                cell = [[NSBundle mainBundle] loadNibNamed:@"RTJHomeCell" owner:self options:nil][2];
                
            }
            cell.delegate = self;

            
        }else{
            
            if (!cell) {
                
                cell = [[NSBundle mainBundle] loadNibNamed:@"RTJHomeCell" owner:self options:nil][8];
                
            }
        }
       
        
    }else if (indexPath.section == 3){
        
        if (!cell) {
            
            cell = [[NSBundle mainBundle] loadNibNamed:@"RTJHomeCell" owner:self options:nil][5];
            
        }
        cell.headerTitle.text = @"精选服务";
        
    }else if (indexPath.section == 4){
        
        if (!cell) {
            
            cell = [[NSBundle mainBundle] loadNibNamed:@"RTJHomeCell" owner:self options:nil][3];
            
        }
        
         if ([self.data[0][@"rec_deal"] isKindOfClass:[ NSArray class]]) {
       
             cell.automarkData = self.data[0][@"rec_deal"][indexPath.row];

         }
    
    }else{
        
        if (!cell) {
            
            cell = [[NSBundle mainBundle] loadNibNamed:@"RTJHomeCell" owner:self options:nil][7];
            
        }
    }
    
    cell.homedata = _dataSource;
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return  cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        
        RTJLoginOrRegisterController *vc = [[RTJLoginOrRegisterController alloc]init];
        LXNavigationViewController *nav=[[LXNavigationViewController alloc]initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
        
    }else if (indexPath.section == 4) {
        
        RTJTenderDetailsController *VC = [[RTJTenderDetailsController alloc]init];
        VC.markId = [NSString stringWithFormat:@"%@",self.data[0][@"rec_deal"][indexPath.row][@"id"]];
        [self.navigationController pushViewController:VC animated:YES];
        
    }else if (indexPath.section == 2){
        
        if (indexPath.row != 0) {
            
            if ([RTJUserTool isLogin]) {
                
                if (indexPath.row == 1) {
                    
                    RTJAutoMarkDetailsController *vc = [[RTJAutoMarkDetailsController alloc]init];
                    vc.markId = [NSString stringWithFormat:@"%@",_dataSource[@"plan_list"][0][@"id"]];
                    [self.navigationController pushViewController:vc animated:YES];
                    
                }else{
                    
                    //智能标
                    if ([RTJUserTool getTheUserModel].user_autobid == 1) {
                        
                        RTJAutomaticBidDetailsController *VC = [[RTJAutomaticBidDetailsController alloc]init];
                        [self.navigationController pushViewController:VC animated:YES];
                        
                    }else{
                        
                        RTJAutomaticBidController *VC = [[RTJAutomaticBidController alloc]init];
                        [self.navigationController pushViewController:VC animated:YES];
                  
                    }
                }
                
            }else{
                
                RTJLoginOrRegisterController *vc = [[RTJLoginOrRegisterController alloc]init];
                LXNavigationViewController *nav=[[LXNavigationViewController alloc]initWithRootViewController:vc];
                [self presentViewController:nav animated:YES completion:nil];
                
            }
            
        }
        
    }else if (indexPath.section == 1){
        
        RTJTenderDetailsController *VC = [[RTJTenderDetailsController alloc]init];
        VC.markId = [NSString stringWithFormat:@"%@",self.dataSource[@"new_deal"][@"id"]];
        VC.isNewBin = YES;
        [self.navigationController pushViewController:VC animated:YES];
        
    }
    
}
#pragma AutoMarkDelegate
-(void)autoMarkId:(NSString *)markId{
    
    RTJAutoMarkDetailsController *vc = [[RTJAutoMarkDetailsController alloc]init];
    vc.markId = markId;
    [self.navigationController pushViewController:vc animated:YES];
    
    
}

#pragma mark - ZXDiscoverHeaderViewDelegate
#pragma mark Banner点击事件
-(void)didSelectedAutoScrollView:(HAutoScrollView *)asView pageIndex:(NSInteger)pIndex {
    
    NSString *url =self.dataSource[@"banner_list"][pIndex][@"data"];
    
    if (url.length!=0) {
        
        RTJHTMLViewController *vc = [[RTJHTMLViewController alloc]init];
        vc.isUrl = YES;
        vc.title = @"详情";
        vc.htmlStr = url;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

#pragma mark
-(void)didSelectedButtonActions:(UIButton *)sender {
    
    
    
}



@end
